package com.service;

import io.netty.channel.Channel;

import com.alibaba.fastjson.JSONObject;
import com.execaction.CmdExecutor;
import com.execaction.CmdTask;
import com.player.User;
import com.player.WorldMgr;
import com.protocol.Protocol;
import com.qy.util.LogUtil;
import com.socket.Command;
import com.util.CommandMgr;
import com.util.MessageUtil;
import com.util.PBMessage;

/**
 * 服务器队列
 * 
 * @author Allen
 * @date 2016年12月13日
 *
 */
public class GameServerHandler{
	
	
	public static CmdExecutor executor;

	static {
		int corePoolSize = 8;
		int maxPoolSize = 64;
		int keepAliveTime = 5;
		int cacheSize = 64;
		executor = new CmdExecutor(corePoolSize, maxPoolSize, keepAliveTime, cacheSize, "GameServerHandler");
	}
	
	JSONObject json;

	public GameServerHandler(JSONObject json) {
		this.json = json;
	}

	public GameServerHandler() {
		this.json = new JSONObject();
	}

	/**
	 * 服务器队列
	 * @param json
	 * @author Allen
	 * @date 2016年12月13日
	 */
	public void execute(JSONObject json, Channel channel) {
		if(!json.containsKey("code")||!json.containsKey("type")){
			return;
		}
		short code = json.getShort("code");
		PBMessage packet = MessageUtil.buildMessage(code, json) ;
		Command cmd = CommandMgr.getCommand(code);
		if (cmd == null) {
			LogUtil.error("not found cmd , code : " + Integer.toHexString(code) + " , userId : " + packet.getId());
			return;
		}
		int type = json.getInteger("type");
		int userId = packet.getId();
		LogUtil.info("服务器接收请求命令号："+code+"====userId="+userId);
		if (userId > 0) {
			User user = null;
			try {
				if (!WorldMgr.isExist(userId,type) && packet.getCode() != Protocol.U_LOGIN) {
					LogUtil.warn("code " + packet.getCode() + " not found player " + userId + ",can not continue execute.");
					return;
				}

				user = WorldMgr.getGamePlayer(userId,type);

				if (user != null) {
					user.enqueue(new CmdTask(cmd, channel, packet, user.getCmdTaskQueue()));
				}
			} catch (Exception e) {
				if (user != null) {
					LogUtil.debug("packet has exception. player is null. ", e);
				} else {
					LogUtil.debug("packet has exception. " , e);
				}
			}
		} else {
			executor.enDefaultQueue(new CmdTask(cmd, channel, packet, executor.getDefaultQueue()));
		}
	}


}
